import React, { useEffect, useRef, useState } from 'react';
import { Button, Col, Row, Modal } from 'antd';
import { eventBus } from '../../utils';
import { PickerItemData } from '../Picker/config';
import { buildCode, buildJson } from './builder';
import { UnControlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
import 'codemirror';
import 'codemirror/mode/javascript/javascript';
import './style.css';

function Toolbar() {
    const [visible, setVisible] = useState(false);
    const dataRef = useRef<PickerItemData[]>();
    const codeRef = useRef<string>();

    useEffect(() => {
        eventBus.on('build:json', data => {
            dataRef.current = data;
        });
    }, []);

    return (
        <div className="panel-toolbar">
            <Row className="tools" gutter={24}>
                <Col span={3}>
                    <Button
                        onClick={() => {
                            codeRef.current = JSON.stringify(
                                buildJson(dataRef.current, document.querySelector('.panel-canvas')),
                                null,
                                2
                            );
                            setVisible(true);
                        }}>
                        生成json
                    </Button>
                </Col>
                <Col span={3}>
                    <Button
                        onClick={() => {
                            codeRef.current = buildCode(dataRef.current, document.querySelector('.panel-canvas'));
                            setVisible(true);
                        }}>
                        生成代码
                    </Button>
                </Col>
            </Row>
            <Modal className="code" width={1000} visible={visible} onCancel={() => setVisible(false)}>
                <CodeMirror
                    value={codeRef.current}
                    options={{
                        mode: 'javascript',
                        theme: 'material',
                        lineNumbers: true
                    }}
                />
            </Modal>
        </div>
    );
}

export default Toolbar;
